package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"taobao/cache"
	"taobao/model"

	"taobao/taobaorpc/internal/svc"
	"taobao/taobaorpc/taobaorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductUpDataLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductUpDataLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductUpDataLogic {
	return &ProductUpDataLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductUpDataLogic) ProductUpData(in *taobaorpc.ProductUpDataRequest) (*taobaorpc.ProductUpDataResponse, error) {
	// todo: add your logic here and delete this line
	var product model.Product
	err := product.FindProductId(model.DB, in.ProductId)
	if err != nil {
		return nil, err
	}
	if product.ID == 0 {
		return nil, fmt.Errorf("商品异常无法修改")
	}
	product = model.Product{
		Model:  gorm.Model{ID: uint(in.ProductId)},
		Name:   in.Name,
		Price:  float64(in.Price),
		Stock:  in.Stock,
		UserId: int(in.UserId),
	}
	err = product.UpdateProduct(model.DB)
	if err != nil {
		return nil, fmt.Errorf("修改失败")
	}
	key := fmt.Sprintf("cart:*:%d", in.ProductId)
	result, _ := cache.Rdb.Keys(l.ctx, key).Result()
	for _, data := range result {
		m := map[string]interface{}{
			"name":  in.Name,
			"price": in.Price,
		}
		cache.Rdb.HMSet(l.ctx, data, m)
	}

	return &taobaorpc.ProductUpDataResponse{
		ProductId: int64(product.ID),
	}, nil
}
